package com.dex4d.ui.mine.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.User;
import com.dex4d.ui.main.activity.TradeConfirmActivity;
import com.dex4d.ui.main.model.Dex4dTrade;
import com.dex4d.ui.main.model.TradeResult;
import com.dex4d.utils.Arith;
import com.dex4d.utils.Commons;

import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chengyuchun on 2018/11/7.
 */
public class AuthoritySwapActivity extends AuthorityReferralActivity {

    @BindView(R.id.tv_remind)
    TextView tv_remind;

    @BindView(R.id.btn_referral)
    Button btn_referral;

    @BindView(R.id.tv_pay_remind)
    TextView tv_pay_remind;

    @BindView(R.id.tv_pay_result)
    TextView tv_pay_result;

    BigInteger mGasPrice;
    @Override
    protected void initToolbar() {
        showBackView();
        showTitle(getString(R.string.swap));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_authority_referral;
    }

    @Override
    protected void initVariables() {
        tv_remind.setText(getString(R.string.swap_remind));
        btn_referral.setVisibility(View.GONE);

        tv_pay_remind.setText(getString(R.string.pay_to_masternode_swap));
        tv_pay_result.setText(getString(R.string.pay_some_eth_result_swap));

        btn_pay.setText(getString(R.string.pay_some_eth,"1"));
    }

    @Override
    protected void loadData() {
        initGasPrice();
        queryAuth(IConstants.CONTRACTSERVICE_ISARBITRAGER); //查询对倒权限
        queryEthBalance(); //查询以太余额
    }
    private void initGasPrice(){
        final RequestParam gasParam = new RequestParam();
        gasParam.setId(1);
        gasParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        gasParam.setMethod(IConstants.CONTRACTSERVICE_GASPRICE);
        gasParam.setParams(Collections.singletonList(User.getInstance().getAddress()));

        //gas price
        JsonApiWrapper
                .serviceApi()
                .requestByParam(gasParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        //服务器传过来的 GasPrice 是十进制
                        mGasPrice =  new BigInteger(result.getResult());
                    }
                });
    }

    private String calculateGasFee(int limitFlag){
        if(mGasPrice == null)
            return "0.0";

        BigInteger gasLimit = Numeric.toBigInt(Dex4dTrade.getHexGasLimit(limitFlag));
        return Convert.fromWei(mGasPrice.multiply(gasLimit).toString(), Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();
    }

    //根据权限与余额加载swap页面
    @Override
    protected void loadView(String authStatus, String dex4dBalance) {
        tv_dex4d_balance.setText(getString(R.string.current_dex4d_amount,dex4dBalance));
        if(Arith.sub(Double.parseDouble(dex4dBalance),1000.00)>0){
            tv_authority_describe.setText(getString(R.string.temporally_available)); //临时权限
            progress_bar.setProgress(100);
            tv_position.setText(100+"%");
        }else{
            try{
                tv_authority_describe.setText(getString(R.string.not_available_currently)); //没有权限
                int progress  = (int)(Arith.div(Double.parseDouble(dex4dBalance),1000.00,2) * 100);
                progress_bar.setProgress(progress);
                tv_position.setText(progress+"%");
            }catch (Exception e){

            }
        }

        if(authStatus.equals("1")){
            //对永久对倒权限
            tv_authority_describe.setText(getString(R.string.permanent_available)); //永久推荐权限

            tv_pay_result.setVisibility(View.VISIBLE);
            tv_pay_result.setText(getString(R.string.pay_some_eth_result_swap));
            ll_pay.setVisibility(View.GONE);

        }else if(authStatus.equals("2")){
            //购买后处于pending状态
            tv_pay_result.setVisibility(View.VISIBLE);
            tv_pay_result.setText(getString(R.string.pay_some_eth_pending_swap));
            ll_pay.setVisibility(View.GONE);
        }else {
            //没有永久对倒权限
            tv_pay_result.setVisibility(View.GONE);
            ll_pay.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.btn_pay)
    public void onViewClick(){
        if(!TextUtils.isEmpty(mEthBalance) && Double.parseDouble(mEthBalance)<1){
            Toast.makeText(this,getString(R.string.eth_balance_remind),Toast.LENGTH_SHORT).show();
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putInt(Commons.BUNDLE_KEYS.TRADE_TYPE,TradeResult.FLAG_BUY_SWAP);
        bundle.putString(Commons.BUNDLE_KEYS.COIN_AMOUNT,"1.000000");
        bundle.putString(Commons.BUNDLE_KEYS.GAS_CONSUMPTION,calculateGasFee(TradeResult.FLAG_BUY_SWAP));
        openActivity(TradeConfirmActivity.class,bundle);

//        final Dex4dTrade dex4dTrade = new Dex4dTrade(this);
//        dex4dTrade.buyArbitrage("1");
//        dex4dTrade.setOnTradeListener(new Dex4dTrade.OnTradeListener() {
//            @Override
//            public void success(TradeResult result) {
//                result.gas = dex4dTrade.getGasLimit(TradeResult.FLAG_BUY_SWAP);
//                Bundle bundle = new Bundle();
//                bundle.putParcelable(Commons.BUNDLE_KEYS.TRADE_RESULT,result);
//                openActivity(PaySwapSuccessActivity.class,bundle);
//                finish();
//            }
//
//            @Override
//            public void error(TradeResult result) {
//
//            }
//        });
    }
}
